.POSIX:

CC = gcc

## ALL C FILES
CORE_FILES = Core/main.c Core/cpuid.c Core/fpu.c

DRIVER_FILES = Drivers/text_video.c

OPTLIB_FILES = OptLib/optlib.c OptLib/memclr.c OptLib/memmove.c OptLib/memcpy.c \
			   OptLib/memcmp.c OptLib/strlen.c OptLib/strtok.c OptLib/strcpy.c

OAPL_FILES = OAPL/init.c OAPL/encryption.c

STDFILES = $(CORE_FILES)
SSEFILES = $(DRIVER_FILES) $(OPTLIB_FILES) $(OAPL_FILES)
CFILES = $(STDFILES) $(SSEFILES)

## All NASM sources that make up the kernel
AFILES = Boot/grub_boot.asm

WARNFLAGS = -IHeaders/ -IHeaders/OptLib/ \
          -ffreestanding -nostdlib -Werror -Wall -Wextra -fomit-frame-pointer \
          -fno-builtin -fno-exceptions \
          -pedantic -pedantic-errors -Wformat-security -Wformat-nonliteral \
          -Wshadow -Wpointer-arith -Wcast-align -Wwrite-strings \
          -Wmissing-prototypes -Wmissing-declarations -Wredundant-decls \
          -Wnested-externs -Winline -Wno-long-long -fno-stack-protector \
          -Wstrict-prototypes -Wno-unused -std=c99

STDFLAGS = -Os -m32 -mtune=i686 -D__DEBUG__ $(WARNFLAGS)
SSEFLAGS = -O2 -m32 -mtune=i686 -D__DEBUG__ $(WARNFLAGS)

## NASM Flags (also takes settings from the environmenmt)
AFLAGS += -Ox
              
## Linker settings (also takes settings from the environment)
LDFLAGS += -nostdlib --fatal-warnings -m elf_i386

###############

## All directories that have to be created before Building
DIRS = Build/ $(addprefix Build/, Boot/ Drivers/ Core/ OptLib/ OAPL/ )

## The file that indicates the directories have been created
MKDIRS = Build/.mkdirs.done

##################

DEPFILES = $(addprefix Build/,$(CFILES:.c=.d))

.PHONY: clean all

## dependency tracking

ifneq ($(MAKECMDGOALS),clean)
-include $(DEPFILES)
endif

$(DEPFILES): Build/%.d: %.c $(MKDIRS)
	./depend.sh Build/$(dir $<) $(CFLAGS) $*.c > $@

$(MKDIRS):
	for i in $(DIRS); do [ -d $$i ] || mkdir -v $$i; done
	touch $@

clean:
	$(RM) -r Build/
	
###############

##Build/libopt.a: $(MKDIRS) Tools/link.ld $(addprefix Build/,$(OPTLIBCFILES:.c=.o))
##	$(LD) $(LDFLAGS) -shared -o $@ $(addprefix Build/,$(OPTLIBCFILES:.c=.o)) 
	
Build/kernel.elf: $(MKDIRS) Tools/link.ld $(addprefix Build/,$(STDFILES:.c=.o) $(SSEFILES:.c=.o) $(AFILES:.asm=.o))
	$(LD) -TTools/link.ld $(LDFLAGS) -o $@ $(addprefix Build/,$(AFILES:.asm=.o) $(CFILES:.c=.o)) -L./ -lgmp

$(addprefix Build/,$(STDFILES:.c=.o)): Build/%.o: Source/%.c
	$(CC) $(STDFLAGS) -c -o $@ $< 

$(addprefix Build/,$(SSEFILES:.c=.o)): Build/%.o: Source/%.c
	$(CC) $(SSEFLAGS) -c -o $@ $< 

$(addprefix Build/,$(AFILES:.asm=.o)): Build/%.o: Source/%.asm
	nasm $(AFLAGS) -f elf32 $< -o $@

all: $(MKDIRS) Build/kernel.elf
	{ \
		cp Build/kernel.elf Tools/isofiles/boot/kernel.elf; \
		cd Tools; \
		genisoimage -R -b boot/grub/stage2_eltorito -no-emul-boot -boot-load-size 4 -boot-info-table -o ../cdrom.iso isofiles; \
	}

	
